#include <func.h>
#define NUM 10000000
#define wants_to_enter_0 p[1]
#define wants_to_enter_1 p[2]
#define turn p[3]
int main(void)
{
    int shmid = shmget(IPC_PRIVATE,4096,IPC_CREAT|0600);
    int * p = (int *)shmat(shmid,NULL,0);
    p[0] = 0;
    wants_to_enter_0 = 0;
    wants_to_enter_1 = 0;
    turn = 0;
    if(fork()){
        for(int i = 0; i < NUM; i++){
            wants_to_enter_0 = 1;
            while (wants_to_enter_1)
            {
                if(turn != 0)
                {
                    wants_to_enter_0 = 0;
                    while (turn != 0) {}
                    wants_to_enter_0 = 1;
                }
            }
            ++p[0];
            turn = 1;
            wants_to_enter_0 = 0;
        }
        wait(NULL);
        printf("total = %d\n", p[0]);
    }
    else {
        for(int i = 0; i < NUM; i++){
            wants_to_enter_1 = 1;
            while(wants_to_enter_0)
            {
                if(turn != 1)
                {
                    wants_to_enter_1 = 0;
                    while(turn != 1){}
                    wants_to_enter_1 = 1;
                }
            }
            ++p[0];
            turn = 0;
            wants_to_enter_1 = 0;
        }
    }
    return 0;
}

